package http.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author fengbo
 * @version 1.0.0
 * @date 2018/12/5 15:10
 * @since JDK 1.8
 */
public class WriteHandler implements CompletionHandler<Integer, ByteBuffer> {

    private AsynchronousSocketChannel channel;

    public WriteHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer byteBuffer) {
        byteBuffer.flip();
        channel.write(byteBuffer);
        closeChannel();
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        closeChannel();
    }

    private void closeChannel() {
        try {
            channel.shutdownOutput();
            channel.shutdownInput();
            channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
